package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**查询行为实体方法实现
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserEquipmentId(Integer userId, Integer equipmentId) {
        //判断userId是否为空
        if(userId!=null){
            //不为空 使用 userId查询行为实体(refId = 用户id type = 用户类型)
            Query query = Query.query(Criteria.where("refId").is(userId));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if(apBehaviorEntry==null){
                //如果不存在基于userId创建实体数据
                ApBehaviorEntry behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setRefId(userId);
                behaviorEntry.setCreatedTime(new Date());
                behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                mongoTemplate.save(behaviorEntry);
            }
            //返回行为实体
            return apBehaviorEntry;
            //判断设备id是否为空
        }else if(equipmentId!=null){
            //不为空 使用设备id查询  行为实体 (refId = 设备id   type = 设备类型)
            Query query = Query.query(Criteria.where("equipmentId").is(equipmentId));
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if(behaviorEntry==null){
                //如果不存在基于设备id创建实体数据
                ApBehaviorEntry behaviorEntry1 = new ApBehaviorEntry();
                behaviorEntry1.setRefId(equipmentId);
                behaviorEntry1.setCreatedTime(new Date());
                behaviorEntry1.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                mongoTemplate.save(behaviorEntry1);
            }
            return behaviorEntry;
        }
        return null;
    }
}
